package com.tang.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

@Slf4j
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String localAddress = ctx.channel().localAddress().toString();
        log.info("链接地址：{}", localAddress);
        String str = "通知：连接建立成功，Address：" + localAddress + "\r\n";
        ctx.writeAndFlush(str);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("{} 断开链接", ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        log.info("{} 发来消息：{}", ctx.channel().localAddress().toString(), msg);
        ctx.writeAndFlush("收到消息：" + msg + "\r\n时间：" + LocalDateTime.now());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.info("{} 异常信息：{}", ctx.channel().localAddress().toString(), cause.getMessage());
        ctx.close();
    }
}
